package com.example.program.view

import android.content.Context
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat.getColor
import androidx.databinding.tool.Context
import com.example.program.R
import com.google.android.material.resources.MaterialResources.getDimensionPixelSize

// CenterTabLayout.kt
class CenterTabLayout<AttributeSet> @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : HorizontalScrollView(context, attrs, defStyleAttr) {

    private val tabContainer: LinearLayout
    private var selectedPosition = 0
    private var tabWidth = 0
    private var tabHeight = 0
    private var indicatorHeight = 4.dp
    private var indicatorColor = Color.RED
    private var textSize = 12.sp

    private var onTabSelectedListener: ((Int) -> Unit)? = null

    init {
        isFillViewport = true
        tabContainer = LinearLayout(context).apply {
            orientation = LinearLayout.HORIZONTAL
            layoutParams = LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
            )
        }
        addView(tabContainer)

        // 从attrs读取自定义属性
        context.obtainStyledAttributes(attrs, R.styleable.CenterTabLayout).apply {
            indicatorHeight = getDimensionPixelSize(
                R.styleable.CenterTabLayout_indicatorHeight,
                indicatorHeight.toInt()
            ).toFloat()
            indicatorColor = getColor(
                R.styleable.CenterTabLayout_indicatorColor,
                indicatorColor
            )
            textSize = getDimensionPixelSize(
                R.styleable.CenterTabLayout_tabTextSize,
                textSize.toInt()
            ).toFloat().sp
            recycle()
        }
    }

    fun setupWithViewPager(viewPager: ViewPager2, tabs: List<TabModel>) {
        tabContainer.removeAllViews()

        tabWidth = (resources.displayMetrics.widthPixels / tabs.size.coerceAtLeast(1))
        tabHeight = 56.dp

        tabs.forEachIndexed { index, tab ->
            val tabView = createTabView(tab, index)
            tabContainer.addView(tabView)

            tabView.setOnClickListener {
                if (selectedPosition != index) {
                    viewPager.setCurrentItem(index, true)
                }
            }
        }

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                selectTab(position)
            }
        })
    }

    private fun createTabView(tab: TabModel, position: Int): View {
        return LayoutInflater.from(context).inflate(
            R.layout.item_center_tab,
            tabContainer,
            false
        ).apply {
            layoutParams = LinearLayout.LayoutParams(tabWidth, tabHeight)

            val icon = findViewById<ImageView>(R.id.tab_icon)
            val text = findViewById<TextView>(R.id.tab_text)
            val redDot = findViewById<View>(R.id.tab_red_dot)
            val badge = findViewById<TextView>(R.id.tab_badge)

            icon.setImageResource(if (position == selectedPosition) tab.selectedIcon else tab.normalIcon)
            text.text = tab.text
            text.setTextColor(ContextCompat.getColor(
                context,
                if (position == selectedPosition) tab.selectedTextColor else tab.normalTextColor
            ))
            text.textSize = textSize.value

            redDot.visibility = if (tab.showRedDot) View.VISIBLE else View.GONE
            badge.visibility = if (tab.badgeCount > 0) View.VISIBLE else View.GONE
            badge.text = if (tab.badgeCount > 99) "99+" else tab.badgeCount.toString()
        }
    }

    private fun selectTab(position: Int) {
        if (position == selectedPosition) return

        // 更新前一个选中项状态
        updateTabView(selectedPosition, false)

        // 更新新选中项状态
        selectedPosition = position
        updateTabView(selectedPosition, true)

        // 滚动到中间
        smoothScrollTo(position * tabWidth - (width / 2 - tabWidth / 2), 0)

        // 执行动画
        animateTabChange(position)

        // 回调监听
        onTabSelectedListener?.invoke(position)
    }

    private fun updateTabView(position: Int, selected: Boolean) {
        val tabView = tabContainer.getChildAt(position) ?: return
        val tab = tabs[position]

        val icon = tabView.findViewById<ImageView>(R.id.tab_icon)
        val text = tabView.findViewById<TextView>(R.id.tab_text)

        icon.setImageResource(if (selected) tab.selectedIcon else tab.normalIcon)
        text.setTextColor(ContextCompat.getColor(
            context,
            if (selected) tab.selectedTextColor else tab.normalTextColor
        ))
    }

    private fun animateTabChange(position: Int) {
        val tabView = tabContainer.getChildAt(position) ?: return
        val icon = tabView.findViewById<ImageView>(R.id.tab_icon)

        // 图标缩放动画
        icon.animate()
            .scaleX(1.2f)
            .scaleY(1.2f)
            .setDuration(200)
            .withEndAction {
                icon.animate()
                    .scaleX(1f)
                    .scaleY(1f)
                    .setDuration(200)
                    .start()
            }
            .start()
    }

    fun setOnTabSelectedListener(listener: (Int) -> Unit) {
        this.onTabSelectedListener = listener
    }

    private val Int.dp: Int get() = (this * resources.displayMetrics.density).toInt()
    private val Float.sp: Float get() = this * resources.displayMetrics.scaledDensity
}